// 城市体检
<template>
  <div class="city-medical-container">
    <split-pane
      :min-percent="13"
      :max-percent="50"
      :default-percent="13"
      split="vertical"
      v-on:resize="resize"
    >
      <template slot="paneL">
        <div class="city-medical-aside">
          <div class="top">
            <el-select
              v-model="query.areaId"
              placeholder="体检城市"
              clearable
              :loading="cityOptionsLoading"
              @change="handleCityChange"
            >
              <el-option
                v-for="item in cityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="query.year"
              placeholder="体检年份"
              clearable
              :loading="yearOptionsLoading"
              @change="handleYearChange"
            >
              <el-option
                v-for="item in yearOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <!-- 左侧菜单树 -->
          <aside-menu
            :list="menuList"
            @select-menu="selectedMenu"
            @open-menu="openedMenu"
            @report="handelReport"
            v-loading="treeLoading"
          />
        </div>
      </template>
      <template slot="paneR">
        <div class="city-medical-main">
          <main-map :init-layer="initLayer" @on-load="mapLoad">
            <use-case
              v-if="mapLoadOk && useCaseRender && caseList.length"
              :map-click="true"
              :data="caseList"
              :menu="menu"
            />
            <map-switcher
              v-if="mapLoadOk"
              :style="{ right: infoRender ? '406px' : '20px' }"
              class="switcher transition-box map-widget"
            />
          </main-map>
        </div>
      </template>
    </split-pane>
    <!-- 信息框 -->
    <info v-model="infoRender" :data="infoData" :menu="menu" />

    <!-- 专题报告弹窗 -->
    <template v-if="view">
      <cus-dialog
        v-model="view"
        :title="title"
        :fileUrl="fileUrl"
        :fileType="fileType"
        @closed="handleClosed"
      ></cus-dialog>
    </template>
    <time-line
      v-if="timeLine.length"
      :current="currentTime"
      :timeLayers="timeLine"
      @changeTimeLine="handleChangeTimeLine"
      :key="123"
    ></time-line>
    <time-line
      v-if="peopleTimeShow"
      :current="peopleCurrent"
      :timeLayers="peopleTimeLine"
      @changeTimeLine="handleChangePeopleTimeLine"
      :key="234"
    ></time-line>
  </div>
</template>

<script>
import aside from './components/aside'
import mainMap from '@v/main-map'
import TimeLine from '@c/map/components/map-timeline'
import info from '@c/info'
import useCase from '@c/use-case'
import splitPane from 'vue-splitpane'
import cusDialog from '@c/cus-dialog'
import mapSwitcher from '@c/map/components/map-switcher'
import { downloadFile } from '@api/city-medical'
import {
  getAreaList,
  getYearList,
  queryDimension,
  getIndicatorByDimensionId,
} from '@api/indicator-manage'
export default {
  name: 'Home',
  provide() {
    const self = this
    return {
      get map() {
        return self.map
      },
    }
  },
  components: {
    'aside-menu': aside,
    'main-map': mainMap,
    info: info,
    'use-case': useCase,
    'split-pane': splitPane,
    'cus-dialog': cusDialog,
    'map-switcher': mapSwitcher,
    TimeLine,
  },
  data() {
    return {
      query: {
        areaId: '',
        year: '',
      },
      cityOptions: [],
      cityOptionsLoading: true,
      yearOptions: [],
      yearOptionsLoading: true,
      title: '专题报告', // 专题报告名称
      infoRender: false, // 显示&隐藏信息框
      useCaseRender: false, // 选中菜单，重新渲染usecase组件
      mapLoadOk: false, // 地图load是否完成
      view: false, // 专题报告弹窗开关
      menu: {},
      map: null,
      initLayer: window.CITY_LAYERS, // 城市体检默认初始化图层
      menuList: [],
      timeLine: [],
      currentTime: null,
      peopleTimeLine: [
        {
          aliasName: '0点',
          geojson: window.geojsonPath + '/geojson/people0_10.geojson',
          name: 'people0',
        },
        {
          aliasName: '1点',
          geojson: window.geojsonPath + '/geojson/people1_10.geojson',
          name: 'people1',
        },
        {
          aliasName: '2点',
          geojson: window.geojsonPath + '/geojson/people2_10.geojson',
          name: 'people2',
        },
        {
          aliasName: '3点',
          geojson: window.geojsonPath + '/geojson/people3_10.geojson',
          name: 'people3',
        },
        {
          aliasName: '4点',
          geojson: window.geojsonPath + '/geojson/people4_10.geojson',
          name: 'people4',
        },
        {
          aliasName: '5点',
          geojson: window.geojsonPath + '/geojson/people5_10.geojson',
          name: 'people5',
        },
        {
          aliasName: '6点',
          geojson: window.geojsonPath + '/geojson/people6_10.geojson',
          name: 'people6',
        },
        {
          aliasName: '7点',
          geojson: window.geojsonPath + '/geojson/people7_10.geojson',
          name: 'people7',
        },
        {
          aliasName: '8点',
          geojson: window.geojsonPath + '/geojson/people8_10.geojson',
          name: 'people8',
        },
        {
          aliasName: '9点',
          geojson: window.geojsonPath + '/geojson/people9_10.geojson',
          name: 'people9',
        },
        {
          aliasName: '10点',
          geojson: window.geojsonPath + '/geojson/people10_10.geojson',
          name: 'people10',
        },
        {
          aliasName: '11点',
          geojson: window.geojsonPath + '/geojson/people12_10.geojson',
          name: 'people11',
        },
        {
          aliasName: '12点',
          geojson: window.geojsonPath + '/geojson/people12_10.geojson',
          name: 'people12',
        },
        {
          aliasName: '13点',
          geojson: window.geojsonPath + '/geojson/people13_10.geojson',
          name: 'people13',
        },
        {
          aliasName: '14点',
          geojson: window.geojsonPath + '/geojson/people14_10.geojson',
          name: 'people14',
        },
        {
          aliasName: '15点',
          geojson: window.geojsonPath + '/geojson/people15_10.geojson',
          name: 'people15',
        },
        {
          aliasName: '16点',
          geojson: window.geojsonPath + '/geojson/people16_10.geojson',
          name: 'people16',
        },
        {
          aliasName: '17点',
          geojson: window.geojsonPath + '/geojson/people17_10.geojson',
          name: 'people17',
        },
        {
          aliasName: '18点',
          geojson: window.geojsonPath + '/geojson/people18_10.geojson',
          name: 'people18',
        },
        {
          aliasName: '19点',
          geojson: window.geojsonPath + '/geojson/people19_10.geojson',
          name: 'people19',
        },
        {
          aliasName: '20点',
          geojson: window.geojsonPath + '/geojson/people20_10.geojson',
          name: 'people20',
        },
        {
          aliasName: '21点',
          geojson: window.geojsonPath + '/geojson/people21_10.geojson',
          name: 'people21',
        },
        {
          aliasName: '22点',
          geojson: window.geojsonPath + '/geojson/people22_10.geojson',
          name: 'people22',
        },
        {
          aliasName: '23点',
          geojson: window.geojsonPath + '/geojson/people23_10.geojson',
          name: 'people23',
        },
      ],
      peopleTimeShow: false,
      peopleCurrent: null,
      // 指标列表
      caseList: [],
      serviceList: [],
      infoData: {},
      fileUrl: '',
      fileType: '',
      treeLoading: false,
    }
  },
  computed: {
    yearAndArea() {
      return this.query.areaId && this.query.year
    },
  },
  watch: {
    infoRender(val) {
      if (val) {
        // 控制图例组件的位置
        let legend = document.getElementsByClassName('legend-control')[0]
        if (legend) {
          legend.style.marginRight = '406px'
        }
      } else {
        let legend = document.getElementsByClassName('legend-control')[0]
        if (legend) {
          legend.style.marginRight = '20px'
        }
      }
    },
    yearAndArea(val) {
      this.menuList = []
      this.infoData = {}
      this.infoRender = false
      if (val) {
        this.treeLoading = true
        this.fetchData()
        queryDimension(this.query).then((res) => {
          if (res.success) {
            if (res.data) {
              const data = res.data.map((item) => {
                return {
                  ...item.indexDimension,
                  index_name: item.indexDimension.name,
                  show_report: true,
                  fileInfo: item.indexFileInfo,
                  id: item.indexDimension.pkid,
                  children: [],
                }
              })
              data.forEach((item) => {
                getIndicatorByDimensionId(item.pkid, 2).then((res1) => {
                  if (res1.success) {
                    // item.children = Object.values(res1.data)
                    //   .filter(item => item !== null)
                    //   .flat();
                    // item.children.unshift({
                    //   name: '分析视角1',
                    //   pkid: index + '100',
                    //   type: 'view',
                    //   children: [
                    //     {
                    //       name: '指标1',
                    //     },
                    //     {
                    //       name: '指标2',
                    //     },
                    //   ],
                    // });
                    // item.children = [
                    //   ...res1.data.indexViewDatasVos.map(view => {
                    //     return {
                    //       ...view.indexViewInfo,
                    //       type: 'view',
                    //       children: view.indexDataInfoVos ?? [],
                    //     };
                    //   }),
                    //   ...res1.data.indexDataInfoVos,
                    // ];
                    if (res1.data.indexDataInfoVos.length) {
                      res1.data.indexDataInfoVos.map((view) => {
                        item.children.push({
                          ...view,
                          type: 'data',
                        })
                      })
                    }

                    res1.data.indexViewDatasVos.map((view) => {
                      if (view.indexDataInfoVos.length) {
                        item.children.push({
                          ...view.indexViewInfo,
                          type: 'view',
                          children: view.indexDataInfoVos ?? [],
                        })
                      }
                    })
                    item.is_single = res1.data.length > 0 ? true : false
                  }
                })
              })
              this.menuList = data
              console.log('this.menulist', this.menuList)
            }
            this.treeLoading = false
          }
        })
      }
    },
  },
  created() {
    this.fetchData(true)
  },
  methods: {
    handleClosed() {
      this.view = false
      this.fileUrl = ''
    },
    fetchData(flag = null) {
      getAreaList().then((res) => {
        if (res.success) {
          this.cityOptions = res.data.map((item) => {
            return {
              value: item.pkid,
              label: item.areaName,
            }
          })
          if (flag && this.cityOptions.length) {
            this.query.areaId = this.cityOptions[0].value
            getYearList(this.query.areaId).then((res) => {
              if (res.success) {
                const data = [...res.data]
                data.sort()
                this.yearOptions = data
                  .map((item) => {
                    return {
                      value: item,
                      label: item + '年',
                    }
                  })
                  .reverse()
                if (flag && this.yearOptions.length) {
                  this.query.year = this.yearOptions[0].value
                }
                this.yearOptionsLoading = false
              }
            })
          }
          this.cityOptionsLoading = false
        }
      })
      // getYearList().then(res => {
      //   if (res.success) {
      //     const data = [...res.data];
      //     data.sort();
      //     this.yearOptions = data
      //       .map(item => {
      //         return {
      //           value: item,
      //           label: item + '年',
      //         };
      //       })
      //       .reverse();
      //     if (flag && this.yearOptions.length) {
      //       this.query.year = this.yearOptions[0].value;
      //     }
      //     this.yearOptionsLoading = false;
      //   }
      // });
    },
    handleCityChange() {
      this.query.year = ''
      getYearList(this.query.areaId).then((res) => {
        if (res.success) {
          const data = [...res.data]
          data.sort()
          this.yearOptions = data
            .map((item) => {
              return {
                value: item,
                label: item + '年',
              }
            })
            .reverse()
          this.yearOptionsLoading = false
        }
      })
    },
    handleYearChange() {
      // console.log(this.query.year);
      getAreaList(this.query.year).then((res) => {
        if (res.success) {
          this.cityOptions = res.data.map((item) => {
            return {
              value: item.pkid,
              label: item.areaName,
            }
          })
          this.cityOptionsLoading = false
        }
      })
    },
    handelReport(val) {
      // console.log(val);
      downloadFile(val.fileInfo.pkid).then((res) => {
        if (res) {
          const downloadLink = document.createElement('a')
          // 设置下载文件名
          downloadLink.download = val.fileInfo.fileName
          // 获取文件后缀
          const fileArr = val.fileInfo.fileName.split('.')
          const fileSuffix = fileArr[fileArr.length - 1]
          this.fileType = fileSuffix
          // console.log(fileSuffix);
          downloadLink.style.display = 'none'
          const blob = new Blob([res.data], { type: 'application/pdf' })
          downloadLink.href = URL.createObjectURL(blob)
          this.fileUrl = downloadLink.href
          // document.body.appendChild(downloadLink);
          // downloadLink.click();
          // document.body.removeChild(downloadLink);
          this.title = val.fileInfo.fileName
          this.view = true
        }
      })
    },
    // 地图加载完成
    mapLoad(e) {
      this.map = e.target
      this.mapLoadOk = true
    },
    resize() {
      // this.map.resize();
    },
    // 改变交通势态地图
    handleChangeTimeLine(time, index) {
      if (this.map.getLayer(`gaode-lukuang-layer-${this.currentTime}`)) {
        this.map.removeLayer(`gaode-lukuang-layer-${this.currentTime}`)
        this.map.removeSource(`gaode-lukuang-layer-${this.currentTime}`)
      }
      this.currentTime = index
      this.map.addLayer({
        id: `gaode-lukuang-layer-${this.currentTime}`,
        type: 'raster',
        source: {
          type: 'raster',
          tiles: [
            // "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=ad593d21889f41b16ab4835848195eb3",
            // "http://online1.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles=pl&scaler=1&p=1",
            window.gaodeUrl +
              '/trafficengine/mapabc/traffictile?v=1.0&;t=1&x={x}&y={y}&z={z}&&t=' +
              time.time,
          ],
          tileSize: 256,
        },
        paint: {},
      })
    },
    handleChangePeopleTimeLine(item, index) {
      if (this.map.getLayer(this.peopleTimeLine[this.peopleCurrent].name)) {
        this.map.removeLayer(this.peopleTimeLine[this.peopleCurrent].name)
        this.map.removeSource(this.peopleTimeLine[this.peopleCurrent].name)
      }
      this.addHot(item.name, item.geojson)
      this.peopleCurrent = index
    },
    removeTraffic() {
      if (this.currentTime) {
        this.map.removeLayer(`gaode-lukuang-layer-${this.currentTime}`)
        this.map.removeSource(`gaode-lukuang-layer-${this.currentTime}`)
        this.map.removeLayer(`gaode-base-layer`)
        this.map.removeSource(`gaode-base-layer`)
        this.currentTime = null
        this.timeLine = []
      }
    },
    removeHot() {
      if (this.peopleCurrent !== null) {
        this.map.removeLayer(this.peopleTimeLine[this.peopleCurrent].name)
        this.map.removeSource(this.peopleTimeLine[this.peopleCurrent].name)
        this.peopleCurrent = null
        this.peopleTimeShow = false
      }
    },
    addHot(name, source) {
      this.map.addSource(name, {
        type: 'geojson',
        data: source,
      })
      this.map.addLayer({
        id: name,
        type: 'heatmap',
        minzoom: 7, // 最小显示层级
        source: name,
        paint: {
          'heatmap-weight': [
            // 比重 这里使用rks（人口数）来决定比重
            'interpolate', // 区间
            ['linear'], // 线性变化
            ['get', 'all_num'],
            0,
            0.01, // 人口数 0～10的时候权重为 0.01
            100,
            0.1, // 人口数 10～50的时候权重为 0.1
            500,
            1, // 人口数 50～200的时候权重为 1
            1000,
            4, // 人口数 200～1000的时候权重为 4
            2000,
            8, // 人口数 1000以上的时候权重为20
          ],
          'heatmap-radius': [
            // 聚合半径
            'interpolate',
            ['linear'],
            ['zoom'],
            0,
            4, // 层级0～18的时候 聚合半径为10
            8,
            6,
            10,
            9.5, // 层级大于18的时候 聚合半径为3
            11,
            20,
            12,
            30,
            13,
            50,
            14,
            5,
          ],
          'heatmap-intensity': [
            'interpolate',
            ['linear'],
            ['zoom'],
            0,
            1,
            9,
            0.5,
            12,
            0.2,
          ],
          'heatmap-opacity': [
            // 透明度
            'interpolate',
            ['linear'],
            ['zoom'],
            10,
            1, // 层级在10和14之间的时候 透明度为1
            11,
            0.9, // 层级在14和18之间的时候 透明度为0.9
            12,
            0.8, // 层级大于18的时候 透明度为0.8
          ],
        },
      })
    },
    getAllServiceInfo(indicator) {
      const allServiceList = []
      // 当前指标的服务
      if (indicator?.mapServiceInfo?.length) {
        allServiceList.push({
          year: indicator.year,
          serviceList: indicator.mapServiceInfo,
        })
      }
      // 关联指标的服务
      if (indicator?.relationIndexInfo) {
        indicator.relationIndexInfo.forEach((item) => {
          // allServiceList.push({
          //   year: item.year,
          //   serviceList: item.mapServiceInfo,
          // });
          // 判断年份是否存在
          const hasYearData = allServiceList.find((_) => _.year === item.year)
          if (hasYearData) {
            hasYearData.serviceList = [
              ...hasYearData.serviceList,
              ...item.mapServiceInfo,
            ]
          } else {
            if (item?.mapServiceInfo?.length) {
              allServiceList.push({
                year: item.year,
                serviceList: item.mapServiceInfo,
              })
            }
          }
        })
      }
      return allServiceList
    },
    // 选中菜单，请求信息
    selectedMenu(menu) {
      // console.log(menu, '==========');
      // this.caseList = menu.mapServiceInfo;
      // 获取当前指标的服务的关联的所有指标的服务
      this.caseList = this.getAllServiceInfo(menu)
      this.useCaseRender = true
      // getServiceByIndicatorId(menu.pkid).then(res => {
      //   if (res.success) {
      //     console.log(123);
      //     this.caseList = res.data;
      //     this.useCaseRender = true;
      //   }
      // });
      this.removeTraffic()
      this.removeHot()
      if (menu.is_single) {
        // 单个菜单，特殊处理
        // 体检报告单独出库
        if (menu.index_name === '体检报告') {
          this.title = '体检报告'
          // this.view = true;
          this.infoRender = false
        }
        if (menu.index_name === '交通势态') {
          const nowDate = new Date()
          let data = new Date(nowDate.getTime() - 1000 * 60 * 60 * 23)
          this.currentTime = 23
          data.setMinutes('0')
          data.setSeconds('0')
          for (let i = 0; i < 24; i++) {
            const time = data.getTime() + i * 1000 * 60 * 60
            this.timeLine.push({
              aliasName: `${new Date(time).getHours()}点`,
              time: time,
            })
          }
          this.map.addLayer({
            id: 'gaode-base-layer',
            type: 'raster',
            source: {
              type: 'raster',
              tiles: [
                // "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=ad593d21889f41b16ab4835848195eb3",
                // "http://online1.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles=pl&scaler=1&p=1",
                'http://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&scl=2&x={x}&y={y}&z={z}',
                // "https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
              ],
              tileSize: 256,
            },
            paint: {},
          })
          this.map.addLayer({
            id: `gaode-lukuang-layer-${this.currentTime}`,
            type: 'raster',
            source: {
              type: 'raster',
              tiles: [
                // "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=ad593d21889f41b16ab4835848195eb3",
                // "http://online1.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles=pl&scaler=1&p=1",
                window.gaodeUrl +
                  '/trafficengine/mapabc/traffictile?v=1.0&;t=1&x={x}&y={y}&z={z}&&t=' +
                  this.timeLine[this.currentTime].time,
              ],
              tileSize: 256,
            },
            paint: {},
          })
        }

        if (menu.index_name === '人口分布') {
          this.peopleTimeShow = true
          this.peopleCurrent = 0
          this.addHot(
            this.peopleTimeLine[this.peopleCurrent].name,
            this.peopleTimeLine[this.peopleCurrent].geojson
          )
        }
        return false
      }
      this.menu = menu

      // 请求信息
      // let hasLayerSource = false;
      // if (res.data[0]?.layer_source) {
      //   hasLayerSource = true;
      //   this.caseList = res.data[0].layer_source.flat(); // 平铺数组（数据错误->二维数组）
      // }
      this.infoData = {
        ...menu,
        index_name: menu.name,
        index_def: menu.introduction,
        index_type: menu.indexTyep,
      }
      this.infoRender = true
      // this.$nextTick(() => {
      //   this.useCaseRender = hasLayerSource; // 重渲染useCase
      // });
      // let req = {
      //   type: 'city',
      //   id: menu.id,
      // };
      // getInfoByMenu(req).then(res => {
      //   if (res.meta.successful) {
      //     let hasLayerSource = false;
      //     if (res.data[0]?.layer_source) {
      //       hasLayerSource = true;
      //       this.caseList = res.data[0].layer_source.flat(); // 平铺数组（数据错误->二维数组）
      //     }
      //     this.infoData = res.data[0];
      //     this.infoRender = true;
      //     this.$nextTick(() => {
      //       this.useCaseRender = hasLayerSource; // 重渲染useCase
      //     });
      //   }
      // });
    },
    // 折叠菜单
    openedMenu(menu) {
      if (menu.type === 'view') {
        this.infoData = menu
        this.infoRender = true
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.city-medical-container {
  height: 100%;
  width: 100%;
  position: relative;
  // display: flex;
  .city-medical-aside {
    width: 100%;
    height: 100%;
    .top {
      display: flex;
      .el-select {
        flex: 1;
        ::v-deep .el-input__inner {
          text-align: center;
        }
      }
    }
  }
  .city-medical-main {
    width: calc(100%);
    height: 100%;
  }
}
.time-line {
  position: absolute;
  bottom: 10px;
  display: flex;
  background: red;
  width: 60%;
  left: 400px;
}
</style>
